﻿using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Hosting;
using EPiServer.PlugIn;
using NUnit.Framework;
using OpenWaves.Reflection;
using OpenWaves.Web;

namespace OpenWaves.Testing.CodeAnalysisRules
{
    public class EPiServerGuiPlugInShouldPointToResourceEmbededAspxOrAscx : ICodeAnalysisRule
    {
        public void Run(Assembly assembly)
        {
            EPiServerInfrastructureStub.EnsureSetup();

            var plugins = assembly.GetTypes().SelectMany(t => t.GetCustomAttributes<GuiPlugInAttribute>());

            var virtualPathProvider = new AssemblyResourceVirtualPathProvider();

            foreach (var plugin in plugins)
            {
                // EPiServer converts plugin urls to absolute paths. AssemblyResourceVirtualPathProvider expects app relative paths.
                var pluginUrl = plugin.Url;
                if (Path.IsPathRooted(pluginUrl))
                    pluginUrl = "~" + pluginUrl;

                Assert.That(pluginUrl, Is.StringEnding(".aspx").Or.StringEnding(".ascx"));

                using (var stream = virtualPathProvider.GetFile(pluginUrl).Open())
                using (var reader = new StreamReader(stream))
                {
                    Assert.That(reader.ReadToEnd(), Is.Not.Empty);
                }
            }
        }
    }
}